package com.weiyi.mashangzhu.Roomer.Activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.Landlord.Activity.AdressActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Adapter.CollectAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.GridAdapter_Price;
import com.weiyi.mashangzhu.Roomer.Adapter.ListAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.MapViewPagerAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.RecommendAdapter2;
import com.weiyi.mashangzhu.Roomer.Adapter.ThemeAdapter;
import com.weiyi.mashangzhu.Roomer.Bean.ActivityBean;
import com.weiyi.mashangzhu.Roomer.Bean.FlagBean;
import com.weiyi.mashangzhu.Roomer.Bean.HouseListBean;
import com.weiyi.mashangzhu.Roomer.Bean.MapInfoBean;
import com.weiyi.mashangzhu.Roomer.Bean.PriceBean;
import com.weiyi.mashangzhu.Roomer.Bean.ThemeHavePageBean;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.Weight.calendartest.MonthTimeAdapter;
import com.weiyi.mashangzhu.Weight.calendartest.entity.DayTimeEntity;
import com.weiyi.mashangzhu.Weight.calendartest.entity.MonthTimeEntity;
import com.weiyi.mashangzhu.Weight.calendartest.entity.UpdataCalendar;
import com.weiyi.mashangzhu.Weight.calendartest.utils.MonthTimeAdapter_SearchList;
import com.weiyi.mashangzhu.Weight.calendartest.utils.SharePreferences;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class SearchListActivity extends BaseActivity {

    @BindView(R.id.line_list)
    View lineList;
    @BindView(R.id.line_map)
    View lineMap;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_xuan)
    TextView tvXuan;
    private TextView startTime;          //开始时间
    private TextView stopTime;           //结束时间
    private RecyclerView reycycler;
    private MonthTimeAdapter_SearchList adapter;
    private ArrayList<MonthTimeEntity> datas;
    public static DayTimeEntity startDay;
    public static DayTimeEntity stopDay;
    SharePreferences isPreferences;
    PullToRefreshListView refreshList;
    private int page = 1;
    List<View> list = new ArrayList<>();
    List<ThemeHavePageBean.DataBean.HouselistBean> houselistBeenlist = new ArrayList<>();
    RecommendAdapter2 collectadapter = null;
    MapView mMapView = null;
    String city, starttime, endtime, site, price, type = "";
    String edit_position = "";
    String edit_oLivetime = "";
    String edit_oCheckouttime = "";
    String edit_price = "";
    String edit_hRoom = "";
    String edit_hPeoples = "";
    String edit_hBedtype = "";
    String edit_hType = "";
    String edit_hMatches = "";
    String address = "";
    String city_name = "";
    List<HouseListBean> houseListBean = new ArrayList<>();
    public LocationClient mLocationClient = null;
    public BDAbstractLocationListener myListener = new MyLocationListener();
    BaiduMap mBaiduMap;
    String starttime_now, endtime_now = "";
    TextView nohouse;
    ViewPager viewPager;
    MapViewPagerAdapter vpadapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_list);
        ButterKnife.bind(this);
        isPreferences = new SharePreferences(this);
        EventBus.getDefault().register(this);
        city = getIntent().getStringExtra("city");
        starttime = getIntent().getStringExtra("starttime");
        endtime = getIntent().getStringExtra("endtime");
        site = getIntent().getStringExtra("site");
        price = getIntent().getStringExtra("price");
        type = getIntent().getStringExtra("type");
        Log.e("qqqqqq", "city=" + city + ",starttime=" + starttime + ",endtime=" + endtime + ",site=" + site + ",price=" + price + ",type=" + type);
        MyApp.person_xuan = "";
        MyApp.room_xuan = "";
        MyApp.bed_type_xuan = "";
        MyApp.facil_xuan = "";
        if (price == null) {
            price = "";
            MyApp.price_xuan = "";
        } else {
            MyApp.price_xuan = price;
        }
        MyApp.flags_type_xuan.clear();
        if (type == null) {
            type = "";
            MyApp.type_xuan = "";

            for (int i = 0; i < 7; i++) {
                MyApp.flags_type_xuan.add(new FlagBean(false));
            }
        } else {
            MyApp.type_xuan = type;
            for (int i = 0; i < 7; i++) {
                MyApp.flags_type_xuan.add(new FlagBean(false));
            }
            String[] strings = type.split(",");
            for (int i = 0; i < strings.length; i++) {
                if (strings[i].equals("1")) {
                    MyApp.flags_type_xuan.get(0).setFlag(true);
                } else if (strings[i].equals("2")) {
                    MyApp.flags_type_xuan.get(1).setFlag(true);
                } else if (strings[i].equals("3")) {
                    MyApp.flags_type_xuan.get(2).setFlag(true);
                } else if (strings[i].equals("4")) {
                    MyApp.flags_type_xuan.get(3).setFlag(true);
                } else if (strings[i].equals("5")) {
                    MyApp.flags_type_xuan.get(4).setFlag(true);
                } else if (strings[i].equals("6")) {
                    MyApp.flags_type_xuan.get(5).setFlag(true);
                }else if (strings[i].equals("7")) {
                    MyApp.flags_type_xuan.get(6).setFlag(true);
                }
            }
        }


        if (starttime == null) {
            starttime = "";
            MyApp.starttime_xuan = "";
        } else {
            MyApp.starttime_xuan = starttime;
        }
        if (endtime == null) {
            endtime = "";
            MyApp.endtime_xuan = endtime;
        } else {
            MyApp.endtime_xuan = endtime;
        }
        if (site == null) {
            site = "";
            MyApp.destination_xuan = "";
        } else {
            MyApp.destination_xuan = site;
        }
        initView();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        tvAddress.setTextColor(getResources().getColor(R.color.colorText));
        tvXuan.setTextColor(getResources().getColor(R.color.colorText));
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    //直接显示第n个item内容
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }

    public void showPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_win_date, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tvDate.setTextColor(getResources().getColor(R.color.colorText));
            }
        });

        startTime = (TextView) contentView.findViewById(R.id.plan_time_txt_start);
        stopTime = (TextView) contentView.findViewById(R.id.plan_time_txt_stop);
        ImageView close = (ImageView) contentView.findViewById(R.id.close);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        reycycler = (RecyclerView) contentView.findViewById(R.id.plan_time_calender);
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(this,   // 上下文
                        LinearLayout.VERTICAL,  //垂直布局,
                        false);

        reycycler.setLayoutManager(layoutManager);

        MoveToPosition(layoutManager, reycycler, isPreferences.getSp().getInt("start_month_position", 0));


        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        // 设置好参数之后再show
        popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
        initData(popupWindow);

    }

    private void initData(final PopupWindow popupWindow) {
        startDay = new DayTimeEntity(0, 0, 0, 0);
        stopDay = new DayTimeEntity(-1, -1, -1, -1);
        datas = new ArrayList<>();

        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;

        datas.add(new MonthTimeEntity(year, month));                //

        for (int i = 0; i < 6; i++) {
            MonthTimeEntity monthTimeEntity = new MonthTimeEntity();
            if (month >= 12) {//明年
                year = c.get(Calendar.YEAR) + 1;
                month = 1;
                monthTimeEntity.setYear(year);
                monthTimeEntity.setMonth(month);
            } else {
                month = month + 1;
                monthTimeEntity.setYear(year);
                monthTimeEntity.setMonth(month);
            }

            datas.add(monthTimeEntity);

        }

        adapter = new MonthTimeAdapter_SearchList(datas, SearchListActivity.this);
        reycycler.setAdapter(adapter);
        adapter.setOnDayItemClickListener(new MonthTimeAdapter_SearchList.OnDayItemClickListener() {
            @Override
            public void OnDayItemClick(View view, int position) {
                isPreferences.updateSp("start_month_position", startDay.getMonthPosition());
                isPreferences.updateSp("start_day_position", startDay.getDayPosition());
                isPreferences.updateSp("end_month_position", stopDay.getMonthPosition());
                isPreferences.updateSp("end_day_position", stopDay.getDayPosition());

                isPreferences.updateSp("start_year", startDay.getYear());
                isPreferences.updateSp("start_month", startDay.getMonth());
                isPreferences.updateSp("start_day", startDay.getDay());

                isPreferences.updateSp("end_year", stopDay.getYear());
                isPreferences.updateSp("end_month", stopDay.getMonth());
                isPreferences.updateSp("end_day", stopDay.getDay());


                Intent i = new Intent();
                i.putExtra("start_year", startDay.getYear());
                i.putExtra("start_month", startDay.getMonth());
                i.putExtra("start_day", startDay.getDay());

                i.putExtra("end_year", stopDay.getYear());
                i.putExtra("end_month", stopDay.getMonth());
                i.putExtra("end_day", stopDay.getDay());
                setResult(RESULT_OK, i);
                starttime_now = startDay.getYear() + "-" + startDay.getMonth() + "-" + startDay.getDay();
                endtime_now = stopDay.getYear() + "-" + stopDay.getMonth() + "-" + stopDay.getDay();
                edit_oLivetime = startDay.getYear() + "-" + startDay.getMonth() + "-" + startDay.getDay();
                edit_oCheckouttime = stopDay.getYear() + "-" + stopDay.getMonth() + "-" + stopDay.getDay();
                MyApp.starttime_xuan = startDay.getYear() + "-" + startDay.getMonth() + "-" + startDay.getDay();
                MyApp.endtime_xuan = stopDay.getYear() + "-" + stopDay.getMonth() + "-" + stopDay.getDay();
                popupWindow.dismiss();
                tvDate.setTextColor(getResources().getColor(R.color.colorText));
                initList(1);
                initMap();

            }
        });
    }

    @Override
    public void initView() {
        super.initView();

        LayoutInflater layoutInflater = getLayoutInflater();
        View view1 = layoutInflater.inflate(R.layout.item_list, null, false);
        View view2 = layoutInflater.inflate(R.layout.item_map, null, false);
        mMapView = (MapView) view2.findViewById(R.id.bmapView);
        viewPager = (ViewPager) view2.findViewById(R.id.vp_houselist);
        refreshList = (PullToRefreshListView) view1.findViewById(R.id.refresh_list);
        nohouse = (TextView) view1.findViewById(R.id.no_house);
        initMap();
        initList(1);
        refreshList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        Log.e("TAG", "onPullDownToRefresh");
                        //这里写下拉刷新的任务
                        new DownGetDataTask().execute();
                    }

                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        Log.e("TAG", "onPullUpToRefresh");
                        new UpGetDataTask().execute();
                    }
                });

        list.add(view1);
        list.add(view2);

        ListAdapter listAdapter = new ListAdapter(this, list);
        vp.setAdapter(listAdapter);
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    lineList.setBackgroundColor(getResources().getColor(R.color.white));
                    lineMap.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    lineMap.setBackgroundColor(getResources().getColor(R.color.white));
                    lineList.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initMap() {
        MapStatusUpdate u = null;
        mBaiduMap = mMapView.getMap();

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                viewPager.setVisibility(View.GONE);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        mBaiduMap.clear();
        // 开启定位图层，一定不要少了这句，否则对在地图的设置、绘制定位点将无效
        mBaiduMap.setMyLocationEnabled(true);
        Log.e("baiiiiii", "=" + city);
        if (city.contains(",") || !site.equals("")) {
            u = MapStatusUpdateFactory.zoomTo(15);
            mBaiduMap.animateMapStatus(u);
        }
        if (city.contains(",")) {
            String[] l = city.split(",");
            city_name = l[2];
            if (site.equals("")) {
                LatLng ll = new LatLng(Double.parseDouble(l[0]), Double.parseDouble(l[1]));
                u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u, 200);
            } else {
                MyApp.changeAddress(mBaiduMap, city_name, site);
            }


        } else {
            city_name = city;
            if (site.equals("")) {
                MyApp.changeAddress(mBaiduMap, city, city);
            } else {
                MyApp.changeAddress(mBaiduMap, city, site);
            }
        }

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        mLocationClient.start();

        OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                .addParams("destination", city_name)
                .addParams("area", MyApp.destination_xuan)
                .addParams("oLivetime", MyApp.starttime_xuan)
                .addParams("oCheckouttime", MyApp.endtime_xuan)
                .addParams("price", MyApp.price_xuan)
                .addParams("hRoom", MyApp.room_xuan)
                .addParams("hPeoples", MyApp.person_xuan)
                .addParams("hBedtype", MyApp.bed_type_xuan)
                .addParams("hType", MyApp.type_xuan)
                .addParams("hMatches", MyApp.facil_xuan)
                .url(API.BaseApi_R + API.SearchMap_Api).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(SearchListActivity.this);
                T.showShort(SearchListActivity.this, "数据获取失败，请稍后再试");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(SearchListActivity.this);
                Gson gson = new Gson();
                List<MapInfoBean> mapInfoBeanList = new Gson().fromJson(response, new TypeToken<List<MapInfoBean>>

                        () {
                }.getType());
                //创建OverlayOptions的集合

                List<OverlayOptions> options = new ArrayList<OverlayOptions>();
                Marker marker;
                //设置坐标点
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if (mapInfoBeanList.size() == 0) {
                    T.showShort(SearchListActivity.this, "此处暂时没有房源");
                    vpadapter = new MapViewPagerAdapter(SearchListActivity.this, mapInfoBeanList);
                    viewPager.setAdapter(vpadapter);
                } else {
                    for (int i = 0; i < mapInfoBeanList.size(); i++) {
                        View view = inflater.inflate(R.layout.item_marker, null);
                        TextView tv = (TextView) view.findViewById(R.id.tv);
                        tv.setText("¥" + mapInfoBeanList.get(i).getHPrice());
                        BitmapDescriptor bitmap = BitmapDescriptorFactory
                                .fromBitmap(getBitmapFromView(view));
                        LatLng point1 = new LatLng(Double.parseDouble(mapInfoBeanList.get(i).getHLat()), Double.parseDouble(mapInfoBeanList.get(i).getHLog()));
                        OverlayOptions option1 = new MarkerOptions()
                                .position(point1)
                                .icon(bitmap);
                        marker = (Marker) mBaiduMap.addOverlay(option1);
                        //使用marker携带info信息，当点击事件的时候可以通过marker获得info信息
                        Bundle bundle = new Bundle();
                        //info必须实现序列化接口
                        bundle.putInt("position", i);
                        marker.setExtraInfo(bundle);
                    }
                    mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            viewPager.setVisibility(View.VISIBLE);
                            Bundle bundle = marker.getExtraInfo();
                            int position = bundle.getInt("position", 0);
                            viewPager.setCurrentItem(position);
                            return true;
                        }
                    });

                    vpadapter = new MapViewPagerAdapter(SearchListActivity.this, mapInfoBeanList);
                    viewPager.setAdapter(vpadapter);
                }
            }

        });
    }

    private Bitmap getBitmapFromView(View view) {
        view.destroyDrawingCache();
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.UNSPECIFIED);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public void initList(final int p) {
        Log.e("==========", "===" + city_name);
        Log.e("==========", "===" + MyApp.destination_xuan);
        Log.e("==========", "===" + MyApp.starttime_xuan);
        Log.e("==========", "===" + MyApp.endtime_xuan);
        Log.e("==========", "===" + MyApp.price_xuan);
        Log.e("==========", "===" + MyApp.room_xuan);
        Log.e("==========", "===" + MyApp.person_xuan);
        Log.e("==========", "===" + MyApp.bed_type_xuan);
        Log.e("==========", "===" + MyApp.type_xuan);
        Log.e("==========", "===" + MyApp.facil_xuan);
        Log.e("==========", "===" + p + "");

        LoadingDialog.show(this);
        OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                .addParams("destination", city_name)
                .addParams("area", MyApp.destination_xuan)
                .addParams("oLivetime", MyApp.starttime_xuan)
                .addParams("oCheckouttime", MyApp.endtime_xuan)
                .addParams("price", MyApp.price_xuan)
                .addParams("hRoom", MyApp.room_xuan)
                .addParams("hPeoples", MyApp.person_xuan)
                .addParams("hBedtype", MyApp.bed_type_xuan)
                .addParams("hType", MyApp.type_xuan)
                .addParams("hMatches", MyApp.facil_xuan)
                .addParams("pagenum", p + "")
                .url(API.BaseApi_R + API.DoSearch).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(SearchListActivity.this);
                T.showShort(SearchListActivity.this, "数据获取失败，请稍后再试");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(SearchListActivity.this);
                Log.e("seeeeeeee", "re=" + response);


                if (p == 1) {

                    houseListBean.clear();
                    houseListBean = new Gson().fromJson(response, new TypeToken<List<HouseListBean>>

                            () {
                    }.getType());
                    Log.e("seeeeeeee", "size=" + houseListBean.size());
                    if (houseListBean.size() == 0) {
                        nohouse.setVisibility(View.VISIBLE);
                        refreshList.setVisibility(View.INVISIBLE);
                    } else {
                        nohouse.setVisibility(View.INVISIBLE);
                        refreshList.setVisibility(View.VISIBLE);
                        collectadapter = new RecommendAdapter2(SearchListActivity.this, "search", houseListBean);
                        refreshList.setAdapter(collectadapter);
                    }


                } else {
                    houseListBean.addAll((Collection<? extends HouseListBean>) new Gson().fromJson(response, new TypeToken<List<HouseListBean>>

                            () {
                    }.getType()));
                    collectadapter.notifyDataSetChanged();
                }
            }
        });


    }

    private class DownGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page = 1;
            initList(page);
            refreshList.onRefreshComplete();
        }
    }

    private class UpGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page += 1;
            initList(page);
            refreshList.onRefreshComplete();
        }
    }


    public void onEventMainThread(UpdataCalendar event) {
        adapter.notifyDataSetChanged();
        startTime.setText(startDay.getMonth() + "月" + startDay.getDay() + "日" + "\n");
        if (stopDay.getDay() == -1) {
            stopTime.setText("结束" + "\n" + "时间");
        } else {
            stopTime.setText(stopDay.getMonth() + "月" + stopDay.getDay() + "日" + "\n");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x001) {
            if (resultCode == 0x002) {
                tvAddress.setTextColor(getResources().getColor(R.color.colorText));
                address = data.getStringExtra("address");
                MyApp.destination_xuan = address;
                site = address;
                initList(1);
                initMap();
                edit_position = address;

            } else if (resultCode == 0x003) {
                tvXuan.setTextColor(getResources().getColor(R.color.colorText));
                initList(1);
                initMap();
            }
        }
    }

    @OnClick({R.id.back, R.id.tv_list, R.id.tv_map, R.id.date, R.id.address, R.id.xuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_list:
                lineList.setBackgroundColor(getResources().getColor(R.color.white));
                lineMap.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                vp.setCurrentItem(0);
                break;
            case R.id.tv_map:
                lineMap.setBackgroundColor(getResources().getColor(R.color.white));
                lineList.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                vp.setCurrentItem(1);
                break;
            case R.id.date:
                showPopupWindow();
                tvDate.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvAddress.setTextColor(getResources().getColor(R.color.colorText));
                tvXuan.setTextColor(getResources().getColor(R.color.colorText));
//                T.showShort(this,"starttime="+starttime_now);

                break;
            case R.id.address:
                tvAddress.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvDate.setTextColor(getResources().getColor(R.color.colorText));
                tvXuan.setTextColor(getResources().getColor(R.color.colorText));
                Intent intent = new Intent(this, Addressctivity.class);
                Log.e("qqqqqq", "city=" + city);
                intent.putExtra("city", city_name);
                startActivityForResult(intent, 0x001);
                break;
            case R.id.xuan:
                tvXuan.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvAddress.setTextColor(getResources().getColor(R.color.colorText));
                tvDate.setTextColor(getResources().getColor(R.color.colorText));
                Intent intent2 = new Intent(this, ScreenActivity.class);
                startActivityForResult(intent2, 0x001);
                break;
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            location.getLatitude();    //获取纬度信息
            location.getLongitude();    //获取经度信息

            MyLocationData locData = new MyLocationData.Builder().latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);


            if (location.getLocType() == BDLocation.TypeGpsLocation) {

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                //当前为网络定位结果，可获取以下信息
                location.getOperators();    //获取运营商信息

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                //当前为网络定位结果

            } else if (location.getLocType() == BDLocation.TypeServerError) {

                //当前网络定位失败
                //可将定位唯一ID、IMEI、定位失败时间反馈至loc-bugs@baidu.com

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                //当前网络不通

            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                //当前缺少定位依据，可能是用户没有授权，建议弹出提示框让用户开启权限
                //可进一步参考onLocDiagnosticMessage中的错误返回码

            }
        }

        /**
         * 回调定位诊断信息，开发者可以根据相关信息解决定位遇到的一些问题
         * 自动回调，相同的diagnosticType只会回调一次
         *
         * @param locType           当前定位类型
         * @param diagnosticType    诊断类型（1~9）
         * @param diagnosticMessage 具体的诊断信息释义
         */
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {

            if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_GPS) {

                //建议打开GPS

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_WIFI) {

                //建议打开wifi，不必连接，这样有助于提高网络定位精度！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_LOC_PERMISSION) {

                //定位权限受限，建议提示用户授予APP定位权限！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_NET) {

                //网络异常造成定位失败，建议用户确认网络状态是否异常！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CLOSE_FLYMODE) {

                //手机飞行模式造成定位失败，建议用户关闭飞行模式后再重试定位！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_INSERT_SIMCARD_OR_OPEN_WIFI) {

                //无法获取任何定位依据，建议用户打开wifi或者插入sim卡重试！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_OPEN_PHONE_LOC_SWITCH) {

                //无法获取有效定位依据，建议用户打开手机设置里的定位开关后重试！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_SERVER_FAIL) {

                //百度定位服务端定位失败
                //建议反馈location.getLocationID()和大体定位时间到loc-bugs@baidu.com

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_FAIL_UNKNOWN) {

                //无法获取有效定位依据，但无法确定具体原因
                //建议检查是否有安全软件屏蔽相关定位权限
                //或调用LocationClient.restart()重新启动后重试！

            }
        }


    }
}
